package com.pkk.cloud.support.oauth2.common.utils;

import com.pkk.cloud.support.admin.oauth2.api.common.resp.Oauth2UserDetails;
import com.pkk.components.moudle.oauth2.AuthUserException;
import com.pkk.components.rpc.common.code.AuthoritiesCode;
import com.pkk.components.rpc.common.code.CommonCode;
import java.util.LinkedHashMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author peikunkun<br>
 * @version V1.0<br>
 * @Title: 用户信息的工具类<br>
 * @Description: <><br>
 * @date 2020/3/18 0018 下午 3:16<br>
 * @URL:[]
 */
@Slf4j
public class UserInfoUtil {

  //使用BCryptPasswordEncoder加密方式
  private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

  /**
   * @Description: 获取用户主题信息从token中
   * <p>
   * 当token无效时,不是一个真正的token,或者获取的token为空时(存在head(Authorization)标签)则会默认的认为主题为游客,设置主题信息为unknown
   * @Param: cls
   * @return: T
   * @Author: peikunkun
   * @Date: 2020/3/20 0020 下午 5:11
   */
  public static <T> T getUserInfo(Class<T> cls) {
    //全局获取认证用户主体信息
    Object userInfo = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (null == userInfo || "unknown".equals(userInfo)) {
      throw new AuthUserException(AuthoritiesCode.CLIENT_VALID_TOKEN_ERROR);
    }
    try {
      T t = cls.newInstance();
      BeanUtils.populate(t, (LinkedHashMap<String, Object>) userInfo);
      return t;
    } catch (Exception e) {
      throw new AuthUserException(AuthoritiesCode.GET_USER_INFO_ERROR, e);
    }
  }

  /**
   * @Description: 对密码进行加密操作
   * @Param: password
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2020/3/20 0020 下午 5:11
   */
  public static String encrypt(String password) {
    return encoder.encode(password);
  }

  /**
   * @Description: 对密码进行比较
   * @Param: rawPassword:原先的密码
   * @Param encodedPassword:编码之后的Miami
   * @return: boolean
   * @Author: peikunkun
   * @Date: 2020/3/20 0020 下午 5:12
   */
  public static boolean match(String rawPassword, String encodedPassword) {
    return encoder.matches(rawPassword, encodedPassword);
  }

  /**
   * @Description: 获取oauth的封装的用户信息
   * @return: com.pkk.cloud.support.admin.oauth2.api.common.resp.Oauth2UserDetails
   * @Author: peikunkun
   * @Date: 2020/3/20 0020 下午 5:12
   */
  public static Oauth2UserDetails getOAuthUserDetails() {
    Object userInfo = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (userInfo == null) {
      throw new AuthUserException(AuthoritiesCode.Unauthorized);
    }
    if (userInfo instanceof Oauth2UserDetails) {
      return (Oauth2UserDetails) userInfo;
    }
    throw new AuthUserException(CommonCode.FAIL);
  }
}
